package adapletplugin.commands;

import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;

import util.MatrixUtils;
import adapletplugin.dialogs.LoadEnoviaDataDialog;

public class LoadEnoviaData extends AbstractHandler
{

	@Override
	public Object execute(ExecutionEvent event) throws ExecutionException
	{
		Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();

		LoadEnoviaDataDialog dialog = new LoadEnoviaDataDialog(shell);
		dialog.create();

		dialog.open();

		if (dialog.getReturnCode() == Window.OK)
		{
			final String typeFile = dialog.getTypeFile();
			final String relationshipFile = dialog.getRelationshipFile();
			final String interfaceFile = dialog.getInterfaceFile();
			final String attributeFile = dialog.getAttributeFile();

			IRunnableWithProgress operation = new IRunnableWithProgress() {

				@Override
				public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
				{
					monitor.beginTask("Load Enovia Data", 5);

					monitor.subTask("Load Type Information");
					MatrixUtils.loadTypesFromFile(typeFile);
					monitor.worked(2);

					monitor.subTask("Load Relationship Information");
					MatrixUtils.loadRelationshipsFromFile(relationshipFile);
					monitor.worked(1);

					monitor.subTask("Load Interface Information");
					MatrixUtils.loadInterfacesFromFile(interfaceFile);
					monitor.worked(1);

					monitor.subTask("Load Attribute Information");
					MatrixUtils.loadAttributesFromFile(attributeFile);
					monitor.worked(1);

					monitor.done();
				}
			};

			ProgressMonitorDialog progMon = new ProgressMonitorDialog(shell);

			try
			{
				progMon.run(true, true, operation);
			} catch (InvocationTargetException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		return null;
	}

}
